/**
 * Copyright 2008-2009 HAN.BIFANG
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */
package han.bashe.business.ejb;

import han.bashe.business.adapter.jms.JmsAdapter;
import han.bashe.business.servicequery.CacheWrapper;
import han.bashe.common.config.Config;
import han.bashe.common.converter.InternalConverter;
import han.bashe.common.converter.JmsConverter;
import han.bashe.common.dao.MessageDao;
import han.bashe.common.entity.BasheEntityConstants;
import han.bashe.common.entity.SoaConversation;
import han.bashe.common.entity.SoaMessageLog;
import han.bashe.common.entity.SoaRequestMessage;
import han.bashe.common.exception.BasheErrorCode;
import han.bashe.common.exception.BasheException;
import han.bashe.common.jms.JmsBindingWrapper;
import han.bashe.common.message.NormalizedMessage;
import han.bashe.common.message.RequestHelper;
import han.bashe.common.schema.ServiceBusUtil;
import han.bashe.common.schema.ServiceInfoWrapper;
import han.bashe.common.util.CommonUtils;

import javax.ejb.ActivationConfigProperty;
import javax.ejb.EJB;
import javax.ejb.MessageDriven;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import v1.message.bashe.han.BasheMessageDocument;
import v1.query.web.bifang.han.ServiceBusDocument.ServiceBus;

/**
 * @Author Kent
 */

@MessageDriven
(mappedName = "han.bashe.services.notify.Queue",
    name = "NotifyMDB",
    activationConfig = {
    @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue")
        }
)
public class NotifyMDB implements MessageListener {
	private static Log log = LogFactory.getLog(NotifyMDB.class);
	
	@EJB
	private LogInterface logBean;
	
	public void onMessage(Message msg) {
		NormalizedMessage req = null;
		try {
			req = JmsConverter.toNormalized((TextMessage)msg);
			log.info("req is " + req);
			RequestHelper rh = new RequestHelper(req);
			String conId = rh.getConversationId();
			
			//change conversation status
			SoaConversation con = MessageDao.findConversation(conId);
			if(con == null || con.getStatus().equals(BasheEntityConstants.STATUS_OK)){
				throw new BasheException(BasheErrorCode.CONVERSATION_NOT_EXISTS_ERROR,"conversation not exists or finished:" + conId);
			}
			
			con.setResponseLogId(rh.getLogId());
			con.setResponseTime(CommonUtils.getNowStr());
			
			con.setStatus(BasheEntityConstants.STATUS_OK);
			logBean.modifyConversation(con);
			
			rh.removeLogId();
			
			
			//check if need notify
			String reqId = con.getRequestLogId();
			SoaMessageLog reqLog = MessageDao.findMessageLog(reqId);
			if(! CommonUtils.isEmpty(reqLog.getReplyServiceCode())){
				rh.removeReplyServiceCode();
				rh.removeReplyServiceVersion();
				
				SoaRequestMessage reqMessage = MessageDao.findRequest(reqId);
				BasheMessageDocument doc = BasheMessageDocument.Factory.parse(reqMessage.getMessage());
				if(!doc.validate()){
					throw new BasheException(BasheErrorCode.PARSE_REQ_XML_ERROR,"parsing conversation request xml error," +
							"request message id is [" + reqId + "]");
				}
				log.info("doc is " + doc);
				NormalizedMessage reqMsg = InternalConverter.bashe2Normalized(doc);
				log.info("reqmsg is " + reqMsg);
				
				
				RequestHelper rh1 = new RequestHelper(reqMsg);
				
				String busCon = rh1.getBusCon();
				if(! CommonUtils.isEmpty(busCon)){
					rh.setConversationId(busCon);
					rh.setServiceCode(rh1.getReplyServiceCode());
					rh.setServiceVersion(rh1.getReplyServiceVersion());
					ServiceInfoWrapper rs = (ServiceInfoWrapper)CacheWrapper.getService(rh1.getReplyServiceCode());
					String busId = rs.getService().getBusRelList().get(0);
					ServiceBus target = CacheWrapper.getServiceBus(busId);
					JmsBindingWrapper jw = ServiceBusUtil.getJmsBinding(target);
					JmsAdapter.call(rh.getMessage(), jw);
					
				}else{
					rh.setServiceCode(rh1.getReplyServiceCode());
					rh.setServiceVersion(rh1.getReplyServiceVersion());
					ServiceBus target = CacheWrapper.getServiceBus(Config.getCurrentBusId());
					JmsBindingWrapper jw = ServiceBusUtil.getJmsBinding(target);
					log.info("jw is " + rh.getMessage());
					JmsAdapter.call(rh.getMessage(), jw);
				}
			
			
			}
			
			
		} catch (Exception e) {
			
			log.error("NotifyMDB error",e);
		}
		
	}

}
